package controllers

import (
	"encoding/json"
	"golanger.com/utils"
	"jk/jklog"
	. "models"
	"net/http"
	// "net/url"
	"time"
)

type FirmwareIndex struct {
	Application
}

func init() {
	App.RegisterController("firmware/", FirmwareIndex{})
}

func (p *FirmwareIndex) Test(rw http.ResponseWriter, req *http.Request) {
	p.Document.Title = p.LANG["test"]
	var f []Firmware
	query := utils.M{
		"mode": "test",
	}
	err := GetFirmwareAllItems(query, &f)
	body := utils.M{}
	if err == nil {
		body["firmware"] = f
	}
	p.Body = body
}

func (p *FirmwareIndex) Upgrade(rw http.ResponseWriter, req *http.Request) {
	p.Document.Title = p.LANG["upgrade"]

	var f []Firmware
	query := utils.M{
		"mode": "upgrade",
	}

	err := GetFirmwareAllItems(query, &f)
	body := utils.M{}
	if err == nil {
		body["firmware"] = f
	}
	p.Body = body
}

func (p *FirmwareIndex) Ownbug(rw http.ResponseWriter, req *http.Request) {
	p.Document.Title = p.LANG["ownbug"]

	var f []Firmware
	query := utils.M{
		"mode": "ownbug",
	}
	err := GetFirmwareAllItems(query, &f)
	body := utils.M{}
	if err == nil {
		body["firmware"] = f
	}
	p.Body = body
}

const FromTimeFormat = "2006-01-02 15:04"

func ParseTimeToAbsolute(beParse string) int64 {
	tt, err := time.Parse(FromTimeFormat, beParse)
	if err != nil {
		jklog.L().Errorln(err)
		return 0
	}
	return tt.Unix()
}

func (p *FirmwareIndex) OwnAddItem(rw http.ResponseWriter, req *http.Request) {
	status := utils.M{
		"status": 0,
	}
	if req.Method == "POST" {
		if _, ok := p.POST["ajax"]; ok {
			query := utils.M{
				"name": p.POST["name"],
			}
			find := Firmware{}
			var err error
			err = GetFirmwareItem(query, &find)
			if err == nil {
				status["status"] = 1 // has exist
			} else {
				// str, _ := url.QueryUnescape(p.POST["content"])
				str := p.POST["content"]
				query["content"] = str
				query["mode"] = p.POST["mode"]
				query["classify"] = p.POST["classify"]
				query["createtime"] = time.Now().Unix()
				query["updatetime"] = time.Now().Unix()
				query["starttime"] = ParseTimeToAbsolute(p.POST["starttime"])
				query["stoptime"] = ParseTimeToAbsolute(p.POST["stoptime"])
				if p.POST["fixed"] == "" {
					query["fixed"] = false
				} else {
					query["fixed"] = true
				}
				query["operate"] = p.POST["operate"]
				// jklog.L().Infoln("start time", query["createtime"], ", stoptime=", query["stoptime"], ", updatetime=", query["updatetime"])
				// return
				err = SaveItemToDB(query)
				if err != nil {
					status["status"] = -2 // write error
				}
			}
		}
	}
	jklog.L().Debug("result: ", status["status"])
	result, _ := json.Marshal(status)
	rw.Write(result)
}

func (p *FirmwareIndex) AddItem(rw http.ResponseWriter, req *http.Request) {
	status := utils.M{
		"status": 0,
	}
	if req.Method == "POST" {
		if _, ok := p.POST["ajax"]; ok {

			query := utils.M{
				"classify": p.POST["classify"],
			}
			find := Firmware{}
			var err error
			if p.POST["mode"] == "test" {
				query["mode"] = "test"
				err = GetFirmwareItem(query, &find)
				if err == nil {
					status["status"] = 1 // exist
				} else {
					// str, _ := url.QueryUnescape(p.POST["content"])
					str := p.POST["content"]
					query["content"] = str
					query["createtime"] = time.Now().Unix()
					query["updatetime"] = time.Now().Unix()
					err = SaveItemToDB(query)
					if err != nil {
						status["status"] = -2
					}
				}
			} else if p.POST["mode"] == "upgrade" {
				query["mode"] = "upgrade"
				err := GetFirmwareItem(query, &find)
				if err == nil {
					status["status"] = 1 // exist
				} else {
					query["content"] = p.POST["content"]
					query["createtime"] = time.Now().Unix()
					query["updatetime"] = time.Now().Unix()
					err = SaveItemToDB(query)
					if err != nil {
						status["status"] = -2
					}
				}
			}
		}
	}
	jklog.L().Debug("result add: ", status["status"])
	result, _ := json.Marshal(status)
	rw.Write(result)
}

func (p *FirmwareIndex) ModItem(rw http.ResponseWriter, req *http.Request) {
	status := utils.M{
		"status": 0,
	}

	if req.Method == "POST" {
		if _, ok := p.POST["ajax"]; ok {

			// need check
			if p.POST["code"] != "jk" {
				status["status"] = -5
			} else {
				query := utils.M{
					"mode": p.POST["mode"],
				}
				if p.POST["name"] == "" {
					query["classify"] = p.POST["classify"]
				} else {
					query["name"] = p.POST["name"]
				}

				// jklog.L().Infoln(p.POST["content"])
				find := Firmware{}
				err := GetFirmwareItem(query, &find)
				if err != nil {
					status["status"] = -1 // not exist
				} else {
					str := p.POST["content"]
					update := utils.M{
						"content":    str,
						"updatetime": time.Now().Unix(),
					}
					if p.POST["fixed"] == "" {
						update["fixed"] = false
					} else {
						update["fixed"] = true
					}
					if p.POST["operate"] != "undefined" {
						update["operate"] = p.POST["operate"]
					}
					err = ModItemToDB(query, update)
					if err != nil {
						status["status"] = -2
					}
				}
			}
		}
	}
	jklog.L().Debug("result mod: ", status["status"])
	result, _ := json.Marshal(status)
	rw.Write(result)
}

func (p *FirmwareIndex) DelItem(rw http.ResponseWriter, req *http.Request) {
	status := utils.M{
		"status": 0,
	}
	if req.Method == "POST" {
		if _, ok := p.POST["ajax"]; ok {
			// check
			if p.POST["code"] != "jkdel" {
				status["status"] = -5
			} else {
				query := utils.M{
					"mode": p.POST["mode"],
				}
				if p.POST["name"] == "" {
					query["classify"] = p.POST["classify"]
				} else {
					query["name"] = p.POST["name"]
				}

				find := Firmware{}
				err := GetFirmwareItem(query, &find)
				if err != nil {
					status["status"] = -1 // not exist
				} else {
					err = DelItemFromDB(query)
					if err != nil {
						status["status"] = -2
					}
				}
			}
		}
	}
	jklog.L().Debug("result del: ", status["status"])
	result, _ := json.Marshal(status)
	rw.Write(result)
}

func (p *FirmwareIndex) SearchItem(rw http.ResponseWriter, req *http.Request) {
	status := utils.M{
		"status": 0,
	}
	var find Firmware
	if req.Method == "POST" {
		if _, ok := p.POST["ajax"]; ok {
			query := utils.M{
				"mode": p.POST["mode"],
			}
			if p.POST["name"] == "" {
				query["classify"] = p.POST["classify"]
			} else {
				query["name"] = p.POST["name"]
			}

			err := GetFirmwareItem(query, &find)
			if err != nil {
				status["status"] = -1 // not exist
				result, _ := json.Marshal(status)
				rw.Write(result)
				return
			}
		}
	}
	jklog.L().Debug("result search: ", status["status"])
	result, _ := json.Marshal(find)
	rw.Write(result)
}
